package com.offcn.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.offcn.pojo.Member;
import com.offcn.service.MemberService;
import com.offcn.service.ReportService;
import com.offcn.utils.MessageConstant;
import com.offcn.utils.Result;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: wy
 * @Date: 2022/9/3 15:40
 */

@RestController
@RequestMapping("report")
public class ReportController {

    private Result result;

    @Reference
    private MemberService memberService;


    @Reference
    private ReportService reportService;

    /*
    对应后台的json数据格式为:
        {
            "data":{
                "setmealNames":["套餐1","套餐2","套餐3"],
                "setmealCount":[{"name":"套餐1","value":10},
                             {"name":"套餐2","value":30},
                             {"name":"套餐3","value":25} ]
            },
            "flag":true,
            "message":"获取套餐统计数据成功"
        }

     */
    //制作 折线图  需要拿到 数据 —— 1： 月份 2： 月份对应的数据
    @RequestMapping("/getMemberReport")
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    public Result getMemberReport() {
        //获取当前月 往前 推12 个月分 包括当前月
        //存放每个月 和 每个语月份 新增的 会员数
        HashMap<Object, Object> map = new HashMap<>();
        try {
            //存放月份的集合
            List<String> months = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            //吧月份 往前面推12 个月  就等于  2021-9
            calendar.add(Calendar.MONTH, -12);
            //遍历月份
            for (int i = 1; i <= 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                //获取 2021 - 10 月份的时间
                Date time = calendar.getTime();
                months.add(new SimpleDateFormat("yyyy-MM").format(time));
            }
            //获取每个月的新增会员数
            List<Integer> memberCount = memberService.findMemberCountByMonths(months);
            //存放数据
            map.put("months", months);
            map.put("memberCount", memberCount);
            return result = new Result(true,
                    MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //套餐预约占比
    @Secured({"ROLE_ADMIN"})
    @RequestMapping("getSetmealReport")
    public Result getSetmealReport() {

        Map<String, Object> map = new HashMap<>();
        //1：查询套餐 预约数量
        //存放的是 每个套餐预约的数量
        List<Map<String, Object>> setmealCount = memberService.findSetmealCount();
        //吧查询到的数据 存放到 map集合中
        map.put("setmealCount", setmealCount);

        //吧套餐 存放到 list 集合中
        ArrayList<String> list = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : setmealCount) {
            String name = (String) stringObjectMap.get("name");
            list.add(name);
        }
        map.put("setmealNames", list);
        return new Result(true, "", map);
    }


    //运营商统计数
    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> map = null;
        try {
            map = reportService.getBusinessReportData();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Result(true, "", map);
    }

    //导出运营商的判断
    @RequestMapping("exportExcel")
    @Secured({"ROLE_ADMIN"})
    public Result exportExcel() {
        result = new Result(true, "", "");
        return result;
    }

    //导出运营商
    @RequestMapping("exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response, HttpServletRequest request) {

        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            //获取表格 位置
            URL url = ReportController.class.getClassLoader().getResource("exceIFile/report_template.xlsx");

            //获取表格
            FileInputStream fis = new FileInputStream(new File(url.toURI()));
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);

            //获取表格中的sheets页
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);

            //获取当前第 3 行 并且 给 第6列插入数据 当前日期
            XSSFRow row3 = sheetAt.getRow(2);
            row3.getCell(5).setCellValue((String) map.get("reportDate"));

            /*会员统计*/
            //获取 第 5 行 并且 给 第6 了存入 新增会员数
            XSSFRow row5 = sheetAt.getRow(4);
            row5.getCell(5).setCellValue((Integer) map.get("todayNewMember"));
            //给 8 列 存入 总会员数
            row5.getCell(7).setCellValue((Integer) map.get("totalMember"));

            //获取 第 6 行 并且 给 第6 了存入 本周会员数
            XSSFRow row6 = sheetAt.getRow(5);
            row6.getCell(5).setCellValue((Integer) map.get("thisWeekNewMember"));
            //本月新增会员数
            row6.getCell(7).setCellValue((Integer) map.get("thisMonthNewMember"));

            /*预约统计*/
            //获取 第 8 行 并且 给 第6 了存入 今日预约数
            XSSFRow row8 = sheetAt.getRow(7);
            row8.getCell(5).setCellValue((Integer) map.get("todayOrderNumber"));
            //给 8 列存入今日 到诊数
            row8.getCell(7).setCellValue((Integer) map.get("todayVisitsNumber"));

            //获取 第 9 行 并且 给 第6 了存入  本周预约数
            XSSFRow row9 = sheetAt.getRow(8);
            row9.getCell(5).setCellValue((Integer) map.get("thisWeekOrderNumber"));
            //本周到诊数
            row9.getCell(7).setCellValue((Integer) map.get("thisWeekVisitsNumber"));

            //获取 第 9 行 并且 给 第6 了存入 本月预约数
            XSSFRow row10 = sheetAt.getRow(9);
            row10.getCell(5).setCellValue((Integer) map.get("thisMonthOrderNumber"));
            //本月到诊数
            row10.getCell(7).setCellValue((Integer) map.get("thisMonthVisitsNumber"));

            List<Map> hotSetmeallist = (List<Map>) map.get("hotSetmeal");
            int rowNum = 12;
            //热门套餐
            for (Map map1 : hotSetmeallist) {
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                String proportion = (String) map1.get("proportion");
                String remark = (String) map1.get("remark");
                XSSFRow rowi = sheetAt.getRow(rowNum++);
                rowi.getCell(4).setCellValue(name);
                rowi.getCell(5).setCellValue(setmeal_count);
                rowi.getCell(6).setCellValue(proportion);
                rowi.getCell(7).setCellValue(remark);
            }
            //文件下载
            //创建响应流对象，以流的形式将文件输出浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //3:获取要下载的文件
            String mimeType = request.getServletContext().getMimeType(url.toString());

            response.setContentType(mimeType);

            //告诉浏览器以下载的方式处理该文件
            response.setHeader("Content-Disposition", "attachment;filename=report_template.xlsx");
            //表格数据写入浏览器
            xssfWorkbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();


        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
